var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/qijie', {useNewUrlParser: true});
mongoose.set('useFindAndModify', false);
var db = mongoose.connection;
var articleSchema = new mongoose.Schema({
  title: String,
  content: String,
  nextUrl: String,
  number: Number
})

var CounterSchea = new mongoose.Schema({
  name: String,
  number: Number
})

var Conter = mongoose.model('conters', CounterSchea)
var Article = mongoose.model('arcile', articleSchema);

// var conter = new Conter({
//   name: 'article',
//   number: 0
// })
// conter.save()
// Conter.findOneAndUpdate(
//   {
//     name: 'article'
//   },
//   {
//     $inc:{number:1}
//   },
//   {
//     new:true
//   }).then(res => {
//     console.log(res)
//   }).catch(err => {
//     console.log(err)
//   })


async function getNextSequenceValue(sequenceName){
  var  sequenceDocument = null;
  await Conter.findOneAndUpdate(
      {
        name: 'article'
      },
      {
        $inc:{number:1}
      },
      {
        new:true
      }).then(res => {
        sequenceDocument = res
      })

  return sequenceDocument
}

async function addAticle(data){
  var num = await getNextSequenceValue()
  console.log(num.number)
  var charpter = new Article({ title: data.title, content: data.content,nextUrl:data.nextUrl,number: num.number});
  charpter.save()
}

module.exports = addAticle